<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList"
      :search-params="searchParams"
    ></SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAdd">新增物资/设备</el-button>
          <el-button type="success" size="mini" icon="el-icon-upload2" @click="showImportDialog">批量导入</el-button>
          <el-button type="info" size="mini" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
          <el-button type="danger" :disabled="selectOptions.length === 0" size="mini" icon="el-icon-delete" @click="onDeleteBath">批量删除</el-button>
        </div>
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            @selection-change="onSelect"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="编号" align="center" prop="code" width="120" />
            <el-table-column label="名称" prop="name" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="类型" align="center" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.type === '物资'" type="success">物资</el-tag>
                <el-tag v-else-if="scope.row.type === '设备'" type="primary">设备</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="分类" prop="idle_category.name" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" prop="specification" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="单位" align="center" prop="unit" width="80" />
            <el-table-column label="数量" align="center" prop="quantity" width="80" />
            <el-table-column label="租售价格" align="center" prop="rental_price" width="120" />

            <el-table-column label="技术状况" align="center" width="100" prop="condition">
            </el-table-column>
            <el-table-column label="状态" align="center" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 'available'" type="success">闲置</el-tag>
                <el-tag v-else type="info">在用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="上架状态" align="center" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.is_public === 1" type="success">上架</el-tag>
                <el-tag v-else-if="scope.row.is_public === 0" type="warning">下架</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="所在地" prop="address" width="150" :show-overflow-tooltip="true" />
            <el-table-column label="归属单位" prop="project_name" width="150" :show-overflow-tooltip="true" />
            <el-table-column label="单位原值" align="right" prop="unit_price" width="120" />
            <el-table-column label="总原值" align="right" prop="total_price" width="120" />
            <el-table-column label="发布人" align="right" prop="create_user_name" width="120" />
            <el-table-column label="操作" fixed="right" width="160px">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" @click="onView(scope.row)">详情</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <!-- 添加/编辑物资设备弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面" prop="post_url">
              <FileUpload v-model="form.post_url"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%" @change="handleTypeChange">
                <el-option label="物资" value="物资"></el-option>
                <el-option label="设备" value="设备"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="fr">
              <el-select-tree
                v-model="form.category_id"
                :data="categoryOptions"
                :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                clearable
                style="width: 100%"
                placeholder="请选择分类"
              ></el-select-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="技术状况" prop="condition">
              <el-select v-model="form.condition">
                <el-option label="良好" value="良好"></el-option>
                <el-option label="一般" value="一般"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位原值" prop="unit_price">
              <el-input-number v-model="form.unit_price" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣率(%)" prop="discount_rate">
              <el-input-number v-model="form.discount_rate" :min="0" :max="100" :step="5" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="租售价格" prop="rental_price">
              <el-input v-model="form.rental_price" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在省市" prop="province">
              <el-cascader
                v-model="locationValue"
                :options="locationOptions"
                @change="handleLocationChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="归属单位" prop="project_name">
              <el-input v-model="form.project_name" placeholder="请输入归属单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="闲置" value="available"></el-option>
                <el-option label="在用" value="reserved"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上架状态" prop="is_public">
              <el-select v-model="form.is_public" placeholder="请选择上架状态" style="width: 100%">
                <el-option label="上架" :value="1"></el-option>
                <el-option label="下架" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息" :rows="3"></el-input>
        </el-form-item>
        <el-row :gutter="20">

          <el-col :span="24">
            <el-form-item label="轮播图" prop="images">
              <FileUpload v-model="form.images" multiple/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="物资/设备详情" :visible.sync="detailVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="编号">{{ detail.code }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag v-if="detail.type === '物资'" type="success">物资</el-tag>
          <el-tag v-else-if="detail.type === '设备'" type="primary">设备</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="分类">{{ detail.category_name }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detail.specification }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detail.unit }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ detail.quantity }}</el-descriptions-item>
        <el-descriptions-item label="技术状况">
          {{ detail.condition }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detail.status === 'available'" type="success">闲置</el-tag>
          <el-tag v-else type="info">在用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="所在地">{{ detail.address }}</el-descriptions-item>
        <el-descriptions-item label="归属单位">{{ detail.project_name }}</el-descriptions-item>
        <el-descriptions-item label="单位原值">{{ detail.unit_price }}</el-descriptions-item>
        <el-descriptions-item label="总原值">{{ detail.total_price }}</el-descriptions-item>
        <el-descriptions-item label="折扣率">{{ detail.discount_rate }}%</el-descriptions-item>
        <el-descriptions-item label="租售价格">{{ detail.rental_price }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- Excel导入弹窗 -->
    <el-dialog top="5vh" title="批量导入物资/设备" :visible.sync="importVisible" width="1200px" :close-on-click-modal="false">
      <excel-import
        :categories="categoryOptions"
        :import-api="batchImport"
        @import-success="onImportSuccess"
        @cancel="importVisible = false"
      ></excel-import>
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http } from "@/api";
import SearchForm from "@/components/SearchForm";
import ExcelImport from "@/components/ExcelImport";
import FileUpload from "@/components/UploadFile.vue";
import { cityList } from "@/views/idle/item/city";

export default {
  name: "IdleItem",
  components: {
    FileUpload,
    SearchForm,
    ExcelImport
  },
  mixins: [crud],
  data() {
    return {
      searchList: [
        { label: '名称', prop: 'name', name: 'input' },
        {
          label: '类型',
          prop: 'type',
          name: 'select',
          options: [
            { label: '物资', value: '物资' },
            { label: '设备', value: '设备' }
          ]
        },
        {
          label: '分类',
          prop: 'category_name',
          name: 'input',
        },
        { label: '所在省份', prop: 'province', name: 'input' },
        { label: '所在城市', prop: 'city', name: 'input' },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          options: [
            { label: '闲置', value: 'available' },
            { label: '在用', value: 'reserved' },
          ]
        }
      ],
      searchParams: {
        name: '',
        type: '',
        category_name: '',
        province: '',
        city: '',
        status: ''
      },
      defaultParams: {
        create_user_id: this.$store.state.user.userInfo.id
      },
      // 表格相关
      request: {
        ...http.idleItem,
      },

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增物资/设备',
      isEdit: false,
      form: this.getDefaultForm(),
      rules: {
        code: [
          { required: true, message: '请输入编号', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 60 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 60 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        category_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },

      // 详情弹窗
      detailVisible: false,
      detail: {},

      // 分类选项
      categoryOptions: [],

      // 省市选项
      locationOptions: cityList,
      locationValue: [],

      // 导入相关
      importVisible: false
    };
  },
  created() {
    this.fetchCategories();
  },
  methods: {
    getDefaultForm() {
      return {
        post_url: '',
        images: '',
        code: '',
        name: '',
        type: '物资',
        category_id: '',
        specification: '',
        unit: '',
        quantity: 1,
        condition: '良好',
        status: 'available',
        province: '',
        city: '',
        address: '',
        project_id: 0,
        project_name: '',
        unit_price: 0,
        total_price: 0,
        discount_rate: 100,
        rental_price: 0,
        remark: '',
        is_public: 1
      };
    },

    fetchCategories() {
      http.idleCategory.tree().then(res => {
        this.categoryOptions = res.data;
        // 更新搜索表单中的分类选项
        const categoryprop = this.searchList.find(item => item.prop === 'category_id');
        if (categoryprop) {
          categoryprop.options = res.data;
        }
      });
    },

    getConditionColor(condition) {
      if (condition < 30) return '#F56C6C';
      if (condition < 70) return '#E6A23C';
      return '#67C23A';
    },

    handleTypeChange(value) {
      // 根据类型重新获取分类
      http.idleCategory.tree({ type: value }).then(res => {
        this.categoryOptions = {
          ...res.data,
          category_id: res.data.category_id || 0
        };
      });
    },

    handleLocationChange(value) {
      if (value && value.length > 0) {
        // 根据ID获取具体省市
        const province = this.locationOptions.find(item => item.value === value[0]);
        const city = province.children?.find(item => item.value === value[1]);
        this.form.province = province.label;
        this.form.city = city.label
        console.log(this.form)
      } else {
        this.form.province = '';
        this.form.city = '';
        this.form.address = '';
      }
    },

    onAdd() {
      this.dialogTitle = '新增物资/设备';
      this.isEdit = false;
      this.form = this.getDefaultForm();
      this.locationValue = [];
      this.dialogVisible = true;
    },

    onEdit(row) {
      this.dialogTitle = '编辑物资/设备';
      this.isEdit = true;
      this.form = { ...row, category_id: row.category_id || '' };
      // 设置省市选择器的值
      if (row.province && row.city) {
        const province = this.locationOptions.find(item => item.label === row.province);
        const city = province ? province.children.find(item => item.label === row.city) : {}
        this.locationValue = [province && province.value || '', city && city.value || ''].filter(Boolean);
      }
      this.dialogVisible = true;
    },

    onView(row) {
      http.idleItem.read(row.id).then(res => {
        this.detail = res.data;
        this.detailVisible = true;
      });
    },

    onDelete(row) {
      this.$confirm('确认删除该物资/设备吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.idleItem.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.onSearch();
        }).catch(error => {
          this.$message.error(error.message || '删除失败');
        });
      }).catch(() => {});
    },
    onDeleteBath() {
      let idList = this.selectOptions.map(item => item[this.deleteKey])
      this.$confirm('确认批量删除该物资/设备吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.idleItem.bathDelete(idList).then(() => {
          this.$message.success('删除成功');
          this.onSearch();
        }).catch(error => {
          this.$message.error(error.message || '删除失败');
        });
      }).catch(() => {});
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // 编辑
            const id = this.form.id;
            http.idleItem.update(id, {
              ...this.form,
              total_price: this.form.unit_price * this.form.quantity
            }).then(() => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.initData();
            }).catch(error => {
              this.$message.error(error.message || '更新失败');
            });
          } else {
            // 新增
            http.idleItem.create(null, {
              ...this.form,
              create_user_id: this.$store.state.user.userInfo.id,
              create_user_name: this.$store.state.user.userInfo.nickname,
              total_price: this.form.unit_price * this.form.quantity
            }).then(() => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.initData();
            }).catch(error => {
              this.$message.error(error.message || '添加失败');
            });
          }
        }
      });
    },

    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetprops();
      }
    },

    // 批量导入相关
    showImportDialog() {
      this.importVisible = true;
    },

    // 批量导入API
    batchImport(data) {
      return http.idleItem.batchImport({ items: data }, {
        create_user_id: this.$store.state.user.userInfo.id,
        create_user_name: this.$store.state.user.userInfo.nickname,
      });
    },

    // 导入成功回调
    onImportSuccess() {
      this.importVisible = false;
      this.initData();
    },

    downloadTemplate() {
      window.open('闲置物资设备清单模版.xlsx', '_blank');
    }
  }
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}
.table-handle {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.table-box {
  margin-bottom: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
</style>
